<?php

namespace app\load\model\oa;

use app\load\loadModel\AdminModel;
use app\load\loadModel\HaiModel;
use app\load\loadModel\OaModel;
use app\load\loadModel\TypeModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\Model;
use think\Paginator;

/**
 * 审批表
 */
class ApproveModel extends Model
{

    protected $name = 'approve';


    /**
     * 列表
     * @param $where
     * @param $limit
     * @param $param
     * @param string $filed
     * @return Paginator
     * @throws DbException
     */
    public function list($where, $limit, $param, string $filed = '*'): Paginator
    {
        return Db::name('Approve')
            ->field($filed)
            ->alias('f')
            ->join('Admin a', 'a.id = f.admin_id', 'left')
            ->join('Department d', 'd.id = f.department_id', 'left')
            ->join('FlowType t', 't.id = f.type', 'left')
            ->where($where)
            ->order('f.id desc')
            ->paginate(['list_rows' => $limit, 'query' => $param])
            ->each(function ($item, $key) {
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                $item['check_user'] = '-';
                if ($item['check_status'] < 2 && !empty($item['check_admin_ids'])) {
                    $check_user = Db::name('Admin')->where('id', 'in', $item['check_admin_ids'])->column('name');
                    $item['check_user'] = implode(',', $check_user);
                }
                return $item;
            });
    }


    /**
     * 详情
     * @param array $where
     * @param string $filed
     * @return ApproveModel|array|mixed|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function info(array $where = [], string $filed = '*')
    {
        return $this->db()->where($where)
            ->field($filed)
            ->filter(function ($vle) {
                $vle['product_list'] = OaModel::PurchaseProduct()->where('approve_id',$vle['id'])->select() ?? [];
                $vle['check_list'] = OaModel::FlowRecord()->list(
                    ['f.action_id' => $vle['id']],
                    'f.id,f.content,f.type,f.status,f.image,f.check_user_id,f.check_time,a.name as admin_name,a.thumb');
                $vle['flow_name'] = OaModel::Flow()->where('id',$vle['flow_id'])->value('name');
                $vle['admin_name'] = AdminModel::Admin()->where('id',$vle['admin_id'])->value('name');
            })
            ->find();

    }


    /**
     * 添加
     * @return int|string
     */
    public function add($data)
    {
        return $this->db()->strict(false)
            ->field(true)
            ->insertGetId($data);
    }
}